import dayjs from "dayjs";

// 扁平化嵌套数组
export function flattenTree<T extends { children?: T[] }>(tree: T[]): T[] {
  return tree.reduce<T[]>((acc, item) => {
    const children = item.children ? flattenTree(item.children) : [];
    return acc.concat({ ...item, children: undefined }, children);
  }, []);
}

// 数组转树结构
export function listToTree<T extends { id: number; pid: number }>(list: T[], pid = 0): T[] {
  return list
    .filter(item => item.pid === pid)
    .map(item => ({
      ...item,
      children: listToTree(list, item.id)
    }));
}

// 时间戳转时间
export function timestampToTime(timestamp: number, format = "YYYY-MM-DD HH:mm:ss"): string {
  return dayjs(timestamp).format(format);
}

// 时间转时间戳
export function timeToTimestamp(time: string): number {
  return dayjs(time).valueOf();
}

// 去除对象中的空字段
export function removeEmptyFields<T extends object>(obj: T): Partial<T> {
  const newObj: Partial<T> = {};
  for (const key in obj) {
    const val = obj[key];
    if (val !== "" && val !== null && val !== undefined && !(Array.isArray(val) && val.length === 0)) {
      newObj[key] = val;
    }
  }
  return newObj;
}

// 数组去重
export function uniqueArray<T>(arr: T[]): T[] {
  return Array.from(new Set(arr));
}
